<template>
  <div style="height: 100%;background-color: white">
    <div class="custBox">
      <div class="operation">
        <div class="operation_left">
          <span v-show="select_num == 0">共{{total}}个客户</span>
          <span v-show="select_num > 0">已选中{{select_num}}个</span>
          <el-button size="mini" style="margin-left: 10px" @click="privatCust" v-if="jurisdiction.customer_private">移入私海</el-button>

          <el-dropdown trigger="click" @command="changeSelect" style="margin: 0 5px" v-if="jurisdiction.customer_distribution || jurisdiction.customer_deletePublic">
            <el-button class="el-dropdown-link" size="mini">
              更多 <i class="el-icon-caret-bottom"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1" v-if="jurisdiction.customer_distribution">分配</el-dropdown-item>
              <el-dropdown-item command="2" v-if="jurisdiction.customer_deletePublic">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="operation_right search">
          <el-autocomplete
            size="mini"
            class="inline-input"
            style="width:220px;margin: 0 10px"
            v-model="input"
            @keyup.enter.native="search"
            @change="replace"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入客户名称/联系人/邮箱查询">
            <el-button slot="append" style="cursor: pointer;" @click="search">
              <i class="el-icon-search"></i>
            </el-button>
          </el-autocomplete>

        </div>
      </div>
      <!--     表头显示字段   -->
      <el-dialog :close-on-click-modal="false" :close-on-press-escape	='false'
        :visible.sync="centerDialogVisible"
        width="300px"
        append-to-body
        :show-close="true"
        @close="closeCustShow"
        center>
          <span slot="title" class="dialog-title">
            客户列表显示字段设置
          </span>
        <div style="height: 300px">
          <el-checkbox-group v-model="copyCheckList" :min="1" @change="changeCheck">
            <div v-for="(value,index3) in showlist" :key="index3" style="padding-left: 85px;margin: 5px 0">
              <el-checkbox :label="value.name" :disabled="value.name =='客户名称' "></el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeCustShow" size="small" type="primary" plain>取 消</el-button>
            <el-button type="primary" @click="custShow" :loading="loading" size="small">保存</el-button>
          </span>
      </el-dialog>
<!--   table   -->
      <div class="table_box" >
        <div class="icon icon_left">
          <span class="icon-shaixuan" @click="centerDialogVisible = true"></span>
        </div>

        <el-table
          v-show="load"
          :header-row-style="{background:'#EAF0F6'}"
          ref="multipleTable"
          :data="tableData"
          @selection-change='selectList'
          tooltip-effect="dark"
          style="width: 100%"
          :height="tableHeight"
          class="table"
          @sort-change="sortChange"
          @row-click="preview">
          <el-table-column
            type="selection"
            :fixed="true"
            width="55">
          </el-table-column>

          <template v-for="(col, index) in headerList">
            <el-table-column
              :width="col.field == 'light' ? 80 : 200"
              :label="col.name"
            >
              <template slot-scope="scope">
                <tableTemplate :col="scope.row" :label="col.field" :jurisdiction="jurisdiction" @jump="toDetail" custType="common"></tableTemplate>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            width="40"
            fixed="right">
          </el-table-column>
          <div slot="empty" style="width: 100%;text-align: left;margin-lrft:-250px">
            <div>
              <img :src="empty" alt="" style="width: 250px" />
            </div>
          </div>
        </el-table>

      </div>
<!-- 分页 -->
      <div class="footer">
        <el-pagination align="right"
                       class="fixed"
                       v-if="total >0"
                       style="minHeight:30px"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="nowPage"
                       :page-sizes="[10, 20, 30, 50]"
                       :page-size="nowSize"
                       layout=" prev,pager, next,  sizes"
                       :total="total">
        </el-pagination>
      </div>

      <el-dialog :visible="privateDialog" center width="400px" :close-on-click-modal="false" :before-close="closePrivate" >
        <p slot="title" class="dialog-title" style="font-size: 13px">移入私海</p>
        <div class="move_group" style="font-size:13px;">
          <span>          转移到分组：</span>
<!--        客户分组  -->
          <el-cascader
            size="small"
            :options="groupOptions"
            v-model="groupId"
            :show-all-levels="false"
            :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'text',
                    children: 'children'}"
            clearable></el-cascader>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closePrivate" size="small">取消</el-button>
          <el-button type="primary" @click="movePrivate" size="small" :loading="loading">确定</el-button>
        </div>
      </el-dialog>
      <!-- 分配 -->
      <el-dialog :visible="distributionDialog" center append-to-body width="480px" :close-on-click-modal="false" style="font-size: 13px" :before-close="closeDistribution">
        <p slot="title" class="dialog-title">分配</p>
        <div style="min-height: 250px">
          <div  style="font-size:13px;text-align: left;height: 100px">
            部门：
            <el-cascader
              size="small"
              :options="section"
              v-model="depId"
              :show-all-levels="false"
              :props="sectionProps"
              clearable></el-cascader>
          </div>
          <div>
            <div style="height: 30px;background: rgb(234, 240, 246); margin-top: 20px;line-height: 34px">
              <span class="table_item" style="width: 70px"></span>
              <span class="table_item" style="width: 80px">员工名</span>
              <span class="table_item" style="width: 80px">账号</span>
              <span class="table_item" style="width: 80px">部门</span>
            </div>
            <div v-for="(item,index) in userOptions" :key="index" style="padding: 5px" v-if="userOptions != undefined && userOptions.length > 0">
              <el-radio v-model="radio" :label="item.id" style="padding-left: 10px">{{item.cc}}</el-radio>
              <span class="table_item" style="width: 80px">{{item.name}}</span>
              <span class="table_item" style="width: 80px">{{item.account}}</span>
              <span class="table_item" style="width: 80px">{{item.deptName}}</span>
            </div>
            <div v-else style="text-align: center">
              暂无数据
            </div>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDistribution" size="small">取消</el-button>
          <el-button type="primary" @click="distribution" :loading="loading" size="small">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible="delete_show" center append-to-body width="400px" :close-on-click-modal="false" :before-close="closeDelete">
        <p slot="title" class="dialog-title">删除客户</p>
        <div style="font-size:13px;text-align: center;line-height: 20px">
          <p style="font-weight: 600">您确定要删除如下{{selectName.length}}个客户吗？</p>
          <p style="margin-top: 5px" class="moreLine">
            <span style="font-weight: 600" v-for="(item,index) in selectName" :key="index"> <span v-if="index != 0">,</span>{{item}} </span>
          </p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDelete" size="small">取消</el-button>
          <el-button type="primary" @click="deleteCust" :loading="loading" size="small">确定</el-button>
        </div>
      </el-dialog>

      <drawer v-if="drawerShow" :custId ="nowId" :visible="visShow" @callback="closeDrawer" :iscommon="true" type="3"></drawer>
      </div>
  </div>
</template>
<script>
    import {querySeaCust,movePrivateSea, deptTree, deleteBatchCust, findUserByCrops, seaAllot, queryCustType, getCustField1,setCustField1, delMarkCust, fullNameStore, findUserByCrop} from '@/api/customer'
    import tableTemplate from '@/components/customer/tableTemplate'
    import drawer from './template/drawer'

    import {mapGetters} from "vuex"
    export default {
        data() {
            return {
                select_num: 0, // 多选的条数
                loading:false, // 按钮loading
                empty:'./img/empty.png',
                load:false,
                drawerShow: false, // 详情页组件
                visShow: false, // 抽屉显隐
                nowId: '', // 当前客户id
                jurisdiction:{}, // 客户权限按钮
                centerDialogVisible: false, // 表头显示
                checkList: [], // 显示表头数组
                copyCheckList: [], // 深拷贝复制选择
                headerList:[], // 选中表头集合，用来遍历表头
                markList: [], // 标记为
                showlist: [], // 显示表头数组
                total: 0, // 总条数
                input: '', // 输入框
                tableData: [],
                selectData: [], // 多选数组
                selectIds: [], // 多选ids
                selectName: [], // 多选姓名
                selectRow: [],
                selectionId: '',
                selectValue: '',
                mergeOptions: [],
                delete_show: false,
                nowData: '', // 当前右键所选中的数据
                nowSize: 10, //当前页显示条数
                delete_type: '', // 删除状态，控制单删还是多选删除
                userId: this.$route.params.userId , // 下属客户id
                sortField: '', // 排序的id
                sortType: '', // 排序方式 （正序倒序）
                typeids: [], // 分组id集合
                lables: [], // 标签id集合
                userTree: [], // 共享，转移数组
                nowPage: 1,
                custId: '',
                tips: [],
                typeId: this.$route.params.typeId ? this.$route.params.typeId : '',
                privateDialog:false,
                groupOptions:[], // 分组数组集合
                treeProps:  {
                    value:'id',             // ID字段名
                    label: 'folderName',         // 显示名称
                    children: 'children'    // 子级字段名
                },
                sectionProps: {
                    checkStrictly: true,
                    value:'id',             // ID字段名
                    label: 'value',         // 显示名称
                    children: 'children'    // 子级字段名
                },
                groupId: [], // 移入私海分组id
                sectionValue:'', // 选中部门id
                section: [], // 部门数组集合
                userOptions: [], // 部门下所有用户
                userVal: '', // 分配的用户id
                distributionDialog: false, // 分配弹窗
                radio: '', // 分配的角色id
                screenHeight: document.documentElement.clientHeight,
                tableHeight: document.documentElement.clientHeight - 177,
                depId:[],
                staffId:''
            }
        },
        components: {
            drawer,
            tableTemplate
        },
        created() {
            this.jurisdiction = this.vaildData(this.permission)
            getCustField1(this.userId).then(res => { // 列表显示字段
                if (res.data.success) {
                    res.data.data.forEach(value =>{
                        value.show = value.isshow == 0 ? false : true
                        if(value.show) {
                            this.checkList.push(value.name)
                            this.headerList.push(value)
                        }
                    })
                    this.showlist = res.data.data
                    this.copyCheckList = this.checkList
                    this.load = true
                }
            })

            findUserByCrop().then(res => { // 公司下所有员工
                if (res.data.success) {
                    this.userTree = res.data.data
                }
            })

            queryCustType().then(res => { // 当前用户的分组
                this.groupOptions = res.data.data
            })

            deptTree().then(res => {
                this.section = res.data.data
            })


            fullNameStore().then(res => { // 输入建议
                this.tips = res.data.data
            })

            this.init()

        },
        mounted() {
            document.addEventListener('click', ()=> {
                this.bus.$emit('closeMenu')
            })
            window.onresize = () => {
                this.$nextTick(() => {
                    this.screenHeight = document.documentElement.clientHeight
                    this.tableHeight = this.screenHeight - 177
                })
            }
        },
        computed: {
            ...mapGetters(["permission"]),
        },
        methods: {
            toDetail(id){
                sessionStorage.setItem("lastpathcus", this.$route.fullPath)
                this.$router.push(`/customer/commonDetail/${id}`);
            },
            privatCust() {
              if(this.selectData.length == 0) {
                  this.$message({
                      type:'warning',
                      message:'请选择要移入私海的客户'
                  })
              } else {
                  this.privateDialog = true
              }
            },
            init() { // 初始化，获得新数据
                querySeaCust(this.typeId, this.input, this.lables.toString(), this.typeids.toString(), this.nowPage,this.nowSize, this.sortField, this.sortType).then(res => { // 查询客户列表
                    if(res.data.success) {
                        this.tableData = res.data.data.records
                        this.total = res.data.data.total // 总页数
                        this.nowPage = res.data.data.current // 当前页数
                    }
                })
            },
            distribution() { // 分配用户
              this.loading = true
                let arr = []
                this.selectData.forEach(value => {
                    arr.push(value.id)
                })
                seaAllot(this.radio, arr.toString()).then(res => {
                  if(res.data.success) {
                      this.$message({
                          type:'success',
                          message: res.data.msg
                      })
                      this.distributionDialog = false
                      this.loading = false
                      this.depId = []
                      this.init()
                      this.bus.$emit('updataCustMenu')
                  }
                }).catch(() => {
                    this.loading = false
                })
            },
            movePrivate() { // 移动到私海
              this.loading = true
              let arr = []
                this.selectData.forEach(value => {
                    arr.push(value.id)
                })
                if(this.groupId.length != 0) {
                    movePrivateSea(this.groupId[this.groupId.length - 1], arr.toString()).then(res => {
                        if(res.data.success) {
                            this.$message({
                                type:'success',
                                message: res.data.msg
                            })
                            this.loading = false
                            this.privateDialog = false
                            this.groupId = []
                            this.init()
                            this.bus.$emit('updataCustMenu')
                        }
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.$message({
                        message: '请先选择分组',
                        type: "success"
                    })
                }
            },

            querySearch(queryString, cb) {
                var tips = this.tips;
                var results = queryString ? tips.filter(this.createFilter(queryString)) : tips;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            search() {
                this.nowPage = 1
              this.init()
            },
            createFilter(queryString) { // 搜索框过滤
                return (restaurant) => {
                    return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            replace() {
                var str = this.input
                this.input = str.replace(/\<|\>/g, '')
            },
            unlabel(custId,markId) { // 取消标签
                delMarkCust(custId,markId).then((res) => {
                    if(res.data.success) {
                        this.$message({
                            type:'success',
                            message:'删除标签成功'
                        })
                        this.init()
                    }
                })
            },
            custShow() { // 更改客户表头设置
                this.loading = true
                this.showlist.forEach((value) => {
                    if (this.copyCheckList.indexOf(value.name) > -1) {
                        value.isshow = 1 // 更改为true
                    } else {
                        value.isshow = 0 //跟改为false
                    }
                })
                setCustField1(this.showlist).then(res => {
                    if (res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        getCustField1().then(res => { // 列表显示字段
                            if (res.data.success) {
                                this.checkList = []
                                this.headerList = []
                                res.data.data.forEach(value =>{
                                    value.show = value.isshow == 0 ? false : true
                                    if(value.show) {
                                        this.checkList.push(value.name)
                                        this.headerList.push(value)
                                    }
                                })
                                this.$nextTick(() => {
                                    this.showlist = res.data.data
                                    this.copyCheckList = this.checkList
                                })
                            }
                        })
                        this.loading = false
                        this.centerDialogVisible = false
                    }
                }).catch(() => {
                    this.loading = false
                })
            },

            closeCustShow() { // 取消客户表头设置
                this.centerDialogVisible = false
                this.copyCheckList = this.checkList
            },

            sortChange(order) { // sort 排序发生变化
                switch(order.prop) {
                    case 'light':
                        this.sortField = 'Light' // 标记
                        break;
                    case 'city':
                        this.sortField = 'country_icon' // 城市
                        break;
                    case 'talkNum':
                        this.sortField = 'talk_num' // 沟通次数
                        break;
                }

                if(order.order == 'ascending') {
                    this.sortType = 'ASC'
                } else {
                    this.sortType = 'Desc'
                }
                this.init()
            },

            deleteCust() { // 删除
                this.loading = true
                let removeArr = []
                this.selectData.forEach(value => {
                    removeArr.push(value.id)
                })
                deleteBatchCust(removeArr).then((res) => {
                    if(res.data.success) {
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        })
                        this.loading = false
                        this.delete_show = false
                        this.init()
                        this.bus.$emit('updataCustMenu')
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            changeCheck(value) { // 设置公司名称为必选
                if(value.indexOf('客户名称') < 0) {
                    this.checkList.push('客户名称')
                }
            },

            selectList(item) { // table的全选
                this.select_num = item.length
                this.selectData = item
                this.selectIds = []
                this.selectName = []
                this.selectData.forEach((value) => {
                    this.selectIds.push(value.id)
                    this.selectName.push(value.fullname)
                })
            },
            rowClass({row, rowIndex}){ // table选中后的样式
                console.log(row)
                if(this.selectRow.includes(rowIndex)){
                    return { "background-color": "#E9F3FD",
                        "color": "#409EFF" }
                }
            },
            handleSizeChange(size) { // 改变每页条数
                this.nowPage = 1
                this.nowSize = size
                this.init()
            },
            handleCurrentChange(page) {
                this.nowPage = page // 当前页设置
                this.init()
            },

            changeSelect(value) { // 更多的选项
                if(this.selectData.length === 0) {
                    let message
                    switch(value) {
                        case '1':
                            message = '分配'
                            break
                        case '2':
                            message = '删除'
                            break
                    }
                    this.$message({
                        message: `请选择您要${message}的客户`,
                        type: "success"
                    })
                } else {
                    switch(value) {
                        case '1':
                            this.distributionDialog = true
                            break
                        case '2':
                            this.delete_type = 'complex' // 多选删除
                            this.delete_show = true
                            break
                    }
                }
            },
            preview(item) { // 右侧抽屉打开
                this.nowId = item.id
                this.visShow = true
                this.drawerShow = true
            },
            closeDrawer() {
                this.visShow = false
                this.drawerShow = false
            },
            closePrivate() {
                this.privateDialog = false
                this.groupId = []
            },
            closeDistribution() {
                this.distributionDialog = false
                this.depId = []
            },
            closeDelete() {
                this.delete_show = false
            },
            changeDep() {
                findUserByCrops(this.staffId).then(res => {
                    this.userOptions = res.data.data
                })
            }
        },
        watch: {
            selectData(value) {
                this.selectRow = []
                if (value.length > 0) {
                    value.forEach((item) => {
                        this.selectRow.push(this.tableData.indexOf(item))
                    })
                }
            },
            depId(value) {
                if(value.length > 0) {
                    this.staffId = value[value.length - 1]
                    this.changeDep()
                }
            }
        }
    }
</script>

<style lang="scss">
  .custBox{
    .el-table__header-wrapper{
      background: rgb(234, 240, 246);
      height: 35px;
      line-height: 35px;
    }
  }
  .el-table__header{
    width: 100% !important;
  }
  .el-table__body{
    width:100% !important;
  }
  .cell{
    .el-rate__icon{
      font-size: 18px;
    }
  }
  .tag{
    .el-icon-close{
      color: white !important;
    }
  }
</style>

<style lang="scss" scoped>
  @import "../../styles/customer";
  .table_item{
    display: inline-block;
  }
</style>

